package com.newway.common.config;

import com.newway.common.context.UserInfoInterceptor;
import com.newway.common.filepath.UploadFilePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableAsync
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    UserInfoInterceptor userInfoInterceptor;

    @Autowired
    UploadFilePath uploadFilePath;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userInfoInterceptor)
                .addPathPatterns("/**/**")
                .excludePathPatterns("/login","/system/file/**");
      }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 所有接口
                .allowedOriginPatterns("*") // 允许所有来源（生产环境建议指定具体域名）
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的 HTTP 方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 允许携带 Cookie
                .maxAge(3600); // 预检请求缓存时间（秒）
    }


    @Bean(name = "asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10); // 核心线程数
        executor.setMaxPoolSize(50); // 最大线程数
        executor.setQueueCapacity(100); // 任务队列容量
        executor.setThreadNamePrefix("Async-Executor-"); // 线程名称前缀
        executor.initialize();
        return executor;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射上传目录为静态资源
        registry.addResourceHandler(uploadFilePath.getMappingPath()+"**")
                .addResourceLocations("file:"+uploadFilePath.getUploadPath())
                .setCachePeriod(3600);
    }
}
